package com.stu.widget;

import com.stu.info.GraphFragment;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class HorLabelsView extends View {
	private String[] hlabels;
	private float min, max;
	private boolean scaleChanged;
	private Paint hTextPaint;
	private int textHeight;
	private GraphFragment graphFragment;
	private int gridX;

	public HorLabelsView(Context context) {
		super( context );
		init();
	}

	public HorLabelsView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}
	
	public HorLabelsView(Context context, AttributeSet attrs, int defaultStyle) {
		super(context, attrs, defaultStyle);
		init();
	}

	private void init() {
		gridX = GraphView.GraphViewConfig.GRID_X;
		graphFragment = null;
		hTextPaint = new Paint();
		hTextPaint.setColor( GraphView.GraphViewConfig.LABEL_COLOR );
		
		Rect r = new Rect();
		hTextPaint.getTextBounds( "1", 0, 1, r );
		textHeight = r.height();
		hlabels = new String[gridX + 1];
		reset();
	}

	public void setFragment( GraphFragment f ) {
		graphFragment = f;
	}

	public void setGrid( int x ) {
		gridX = x;
		hlabels = new String[gridX + 1];
		reset();
	}
	
	public void reset() {
		min = 0;
		max = gridX;
		scaleChanged = true;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		if( graphFragment == null )
			return;

		if( graphFragment.maxX > gridX ) {
			max = graphFragment.maxX;
			scaleChanged = true;
		}
		
		if( graphFragment.minX > min ) {
			min = graphFragment.minX;
			scaleChanged = true;
		}

		int w = getWidth();
		if( scaleChanged ) {
			float dx = (1.0f / (float)gridX) * (max - min);
			float val = min;
			for (int i = 0; i <= gridX; i++) {
				hlabels[i] = GraphFragment.formatLabel(val, true);
				val += dx;
			}
			scaleChanged = false;
		}
		float dx = w / gridX;
		float x = 0;
		float h = getHeight() - textHeight;
		for (int i = 0; i <= gridX; i++) {
			if( i == 0 )
				hTextPaint.setTextAlign( Align.LEFT );
			else if( i == gridX )
				hTextPaint.setTextAlign( Align.RIGHT );
			else
				hTextPaint.setTextAlign(Align.CENTER);
			canvas.drawText(hlabels[i], x, h, hTextPaint);
			x += dx;
		}
	}
}
